﻿using System;
using System.Text;
using log4net;
using TdxApiPool.Invoker;

namespace TdxApiPool.Connect
{
    public class TdxConnection
    {
        private static readonly ILog Log = LogManager.GetLogger("TdxConnection");

        public string Ip { get; }
        public int Port { get; }
        public DllInvoker Invoker { get; }
        public bool Connected { get; set; }
        public long Delay { get; set; }
        private volatile bool _usering;
        public string ConnectionName { get; set; }
        public string ConnectionTag { get; set; }
        public int ConnectTime = 0;

        private readonly object _lock = new object();

        public bool IsUsing()
        {
            bool b = false;
            lock (_lock)
            {
                b = _usering;
            }
            return b;
        }

        /// <summary>
        /// 获取除权除息信息
        /// </summary>
        /// <param name="market">市场id集合</param>
        /// <param name="zqdm">股票代码集合</param>
        /// <param name="result">结果集</param>
        /// <param name="errInfo">错误信息</param>
        /// <returns></returns>
        public bool GetXdxrInfo(byte market, string zqdm, StringBuilder result, StringBuilder errInfo)
        {
            lock (_lock)
            {
                _usering = true;
            }

            return false;
        }

        /// <summary>
        /// 连接通达信服务器
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            ConnectTime++;
            StringBuilder result = new StringBuilder(1024 * 1024);
            StringBuilder errInfo = new StringBuilder(256);
            QuoteDelegate.TdxHq_Connect connectDelegate =
                (QuoteDelegate.TdxHq_Connect) Invoker.Invoke("TdxHq_Connect", typeof(QuoteDelegate.TdxHq_Connect));
            Connected = connectDelegate(Ip, Port, result, errInfo);

            Log.Info("------------------------------");
            Log.Info("重连服务器:" + result);
            Log.Info("IP:" + Ip);

            if (!Connected)
            {
                Log.Error("errInfo:" + errInfo);
                Log.Error("重连失败");
            }

            Log.Error("------------------------------");

            return Connected;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="invoker"></param>
        public TdxConnection(string ip, int port, DllInvoker invoker)
        {
            Ip = ip;
            Port = port;
            Invoker = invoker;
        }
    }
}